//------------------------------------------------------------------------------
// Copyright (c) 2008 www.dnaide.com
// Licensed under the MIT (MIT-LICENSE.txt)
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.Compression;

using DNAide.Core;

namespace DNAide.IO
{
	/// <summary>
	/// File helper methods
	/// </summary>
	public static partial class FileAide
	{

		public static void Compress(string source)
		{
			if (string.IsNullOrEmpty(source))
			{
				throw new ArgumentException("Source is required");
			}
			string destination = source + ".gz";
			Compress(source, destination, CompressionAlgorithmType.GZip);
		}


		public static void Compress(string source, CompressionAlgorithmType compressionAlgorithm)
		{
			if (string.IsNullOrEmpty(source))
			{
				throw new ArgumentException("Source is required");
			}
			string destination;
			if (compressionAlgorithm == CompressionAlgorithmType.GZip)
			{
				destination = source + ".gz";
			}
			else
			{
				destination = source + ".z";
			}
			Compress(source, destination, compressionAlgorithm);
		}


		public static void Compress(string source, string destination, CompressionAlgorithmType compressionAlgorithm)
		{
			
			if (string.IsNullOrEmpty(source) || string.IsNullOrEmpty(destination))
			{
				throw new ArgumentException("Both source and destination are required");
			}
			if (compressionAlgorithm == CompressionAlgorithmType.None)
			{
				return;
			}

			if (!File.Exists(source))
			{
				throw new ArgumentException("Source does not exist.");
			}


			FileStream sourceFs, destinationFs;
			byte[] buffer;

			sourceFs = new FileStream(source, FileMode.Open);
			buffer = new byte[sourceFs.Length];
			sourceFs.Read(buffer, 0, buffer.Length);
			sourceFs.Close();

			destinationFs = new FileStream(destination, FileMode.Create);

			if (compressionAlgorithm == CompressionAlgorithmType.GZip)
			{
				GZipStream gzipStream = new GZipStream(destinationFs, CompressionMode.Compress);
				gzipStream.Write(buffer, 0, buffer.Length);
				gzipStream.Close();
			}
			else
			{
				DeflateStream deflateStream = new DeflateStream(destinationFs, CompressionMode.Compress);
				deflateStream.Write(buffer, 0, buffer.Length);
				deflateStream.Close();
			}
			
			destinationFs.Close();
		
		}

	}
}
